import { createApp } from 'vue'
import { createPinia } from 'pinia'
import cloudbase from "@cloudbase/js-sdk"
import App from './App.vue'
import router from './router'
import store from './store'
import axios from 'axios'
import * as ElementPlusIconsVue from '@element-plus/icons-vue'
import 'element-plus/dist/index.css'
import * as vant from 'vant';
import { Uploader } from 'vant';
import { Image as VanImage } from 'vant';
import ElementPlus from 'element-plus'

const app = createApp(App);

// 初始化 CloudBase
const appCloud = cloudbase.init({
  env: "cloud1-2gozbkkk09f11d05",
  region: "ap-shanghai"
});

// 使用全局单例模式处理认证
let authPromise = null;

const initAuth = async () => {
  if (!authPromise) {
    const auth = appCloud.auth();
    authPromise = auth.signInAnonymously().then(() => {
      console.log('CloudBase 认证成功');
      return auth;
    }).catch(err => {
      console.error('CloudBase 认证失败:', err);
      authPromise = null;
      throw err;
    });
  }
  return authPromise;
};

// 全局云函数调用方法
const callCloudFunction = async (name, data) => {
  try {
    await initAuth();
    const result = await appCloud.callFunction({
      name,
      data
    });
    return result;
  } catch (err) {
    console.error(`调用云函数 ${name} 失败:`, err);
    throw err;
  }
};

// 将 cloudbase 和认证方法挂载到全局属性
app.config.globalProperties.$cloudbase = cloudbase;
app.config.globalProperties.$appCloud = appCloud;
app.config.globalProperties.$initAuth = initAuth;
app.config.globalProperties.$callCloudFunction = callCloudFunction;

// 确保在应用启动时进行一次认证
initAuth();

for (const [key, component] of Object.entries(ElementPlusIconsVue)) {
    app.component(key, component)
};

for (const [componentName, component] of Object.entries(vant)) {
    app.component(componentName, component);
}

const pinia = createPinia()

// 将Pinia添加到应用中
app.use(pinia)
app.use(router);
app.use(store);
app.use(Uploader);
app.use(VanImage);
app.use(ElementPlus);
app.mount('#app');